<?php

/* 资金管理控制器 */
class My_moneyApp extends MemberbaseApp
{
    /* 构造函数 */
    function __construct()
    {
         $this->My_moneyApp();
    }

    function My_moneyApp()
    {
        parent::__construct();
		$this->my_money_mod =& m('my_money');
		$this->my_moneylog_mod =& m('my_moneylog');

    }
 	function index()//默认显示
    {
		$user_id = $this->visitor->get('user_id');
		$page = $this->_get_page();	
        $con = array(
            array(      //按收支类型搜索
                'field' => 'leixing',
                'name'  => 'type',
            ),		
            array(      //按下单时间搜索,起始时间
                'field' => 'add_time',
                'name'  => 'add_time_from',
                'equal' => '>=',
                'handler'=> 'gmstr2time',
            ),
            array(      //按下单时间搜索,结束时间
                'field' => 'add_time',
                'name'  => 'add_time_to',
                'equal' => '<=',
                'handler'=> 'gmstr2time_end',
            ),
        );
        $conditions = $this->_get_query_conditions($con);
		$my_money=$this->my_moneylog_mod->find(array(
            'conditions' => "user_id='$user_id' and user_log_del=0 and caozuo=1" . $conditions,
			'order' => 'add_time desc',
            'limit' => $page['limit'],
			'count' => true,
        ));	
		foreach ($my_money as $key => $mymoney)
		{
			if ($mymoney['s_and_z'] == 1){
				$my_money[$key]['money_sr'] = $mymoney['money'];//收入
			}elseif ($mymoney['s_and_z'] == 2){
				$my_money[$key]['money_zc'] = $mymoney['money'];//支付
			}
		}
		//收入、支出总计
		$sql_sr= "SELECT sum(money) as money_total FROM {$this->my_moneylog_mod->table} WHERE user_id='$user_id' and user_log_del=0 and caozuo=1 and s_and_z=1 ". $conditions;
		$sql_zc= "SELECT sum(money) as money_total FROM {$this->my_moneylog_mod->table} WHERE user_id='$user_id' and user_log_del=0 and caozuo=1 and s_and_z=2 ". $conditions;
		$money_total['money_sr_total'] = $this->my_moneylog_mod->getOne($sql_sr);
		$money_total['money_zc_total'] = $this->my_moneylog_mod->getOne($sql_zc);		
		$page['item_count'] = $this->my_moneylog_mod->getCount();
        $this->_format_page($page);
	    $this->assign('page_info', $page);
		$this->assign('my_money', $my_money);	
		$this->assign('money_total', $money_total);	
		$this->assign('money_money', $money_money);

		$this->_config_seo('title', Lang::get('member_center') . ' - ' . Lang::get('my_money_index'));
	    $this->import_resource(array('script' => 'inline_edit.js,jquery.ui/jquery.ui.js,jquery.ui/i18n/' . i18n_code() . '.js',
									'style'=> 'jquery.ui/themes/ui-lightness/jquery.ui.css'));	   
		$money_money=$this->my_money_mod->getRow("select money,money_dj,rz_is_ok from ".DB_PREFIX."my_money where user_id='$user_id'");	
		$this->assign('money_money', $money_money);	
		$this->display('my_money.index.html');
    }
	function remit_alipay()//网上充值
	{
		if ($_POST)
		{
			$money = empty($_POST['money']) ? 0 : htmldecode($_GET['money']);
			$ebank_type = 'alipay';
			if ( $money <= 0)
			{
                $this->show_warning('couwu_pay_money_err'); 
                return;
			}
			if (empty($ebank_type))
			{
                $this->show_warning('couwu_pay_bank_err'); 
                return;
			}			

			//添加日志
			$log_text =$this->visitor->get('user_name').'账户现金充值'.$money.Lang::get('yuan');
			$add_mymoneylog=array(
				'user_id'=>$this->visitor->get('user_id'),
				'user_name'=>$this->visitor->get('user_name'),
				'bank_name'=>$ebank_type,
				'add_time'=>gmtime(),
				'leixing'=>30, //帐号充值	
				//'money_zs'=>$money,
				'money'=>$money,
				'log_text'=>$log_text,		
				's_and_z'=>1,//收入1,支出2	
				'pay_order_sn'=> $this->_gen_order_sn(),//生成支付订单
			);
			$id = $this->my_moneylog_mod->add($add_mymoneylog);
			if ($this->my_moneylog_mod->has_error())
			{
				$this->show_warning($this->my_moneylog_mod->get_error());
				return;
			}			
			header('Location:index.php?app=cashier&act=payment&pay_step=2&id=' . $id);
			//header('Location:index.php?app=my_money&act=remit_ailpay_confirm&id=' . $id);
		}else{
			$user_id = $this->visitor->get('user_id');
			$money_money=$this->my_money_mod->getOne("select money from ".DB_PREFIX."my_money where user_id='$user_id'");		
			$this->assign('money_money', $money_money);
            $this->_config_seo('title', '我要充值 - ' . Conf::get('site_name'));
			$this->assign('curitem', '我要充值');		
			$this->display('my_money.remit_alipay.html');
		}
	}

	//修改支付密码
	function setpaypassword()
	{     	
		$user_id = $this->visitor->get('user_id');
		//读原始密码
		$money_pass=$this->my_money_mod->getOne("select zf_pass from ".DB_PREFIX."my_money where user_id='$user_id'");	
		if($_POST)//检测是否提交
		{			
			$y_password = htmldecode($_GET['y_password']);
			$new_password = htmldecode($_GET['new_password']);
			$confirm_password = htmldecode($_GET['confirm_password']);
			//转换32位 MD5
			$md5y_pass=md5($y_password);
			$md5zf_pass=md5($new_password);				
			if(empty($y_password) || empty($new_password))
			{
				$this->show_warning('密码不能为空'); 
				return;
			}
			if($new_password != $confirm_password)
			{
				$this->show_warning('支付密码与确认新支付密码不一致'); 
				return;
			}
			//判断是否已经输入过支付密码了，没有的话就使用登录密码来判断
			if ($money_pass)//没有输入过支付密码的
			{
				if($money_pass != $md5y_pass)
				{
					$this->show_warning('旧支付密码错误 '); 
					return;	
				}				
			}else{						
				$member_mod = & m('member');
				$user_name=$member_mod->getOne("select user_name from ".DB_PREFIX."member where user_id='$user_id'");	
				$ms =& ms();
				$user_id = $ms->user->auth($user_name, $y_password);
				if (!$user_id)
				{
					/* 未通过验证，提示错误信息 */
					$this->show_warning($ms->user->get_error());
					return;
				}						
			}

			$newpass_array=array( 'zf_pass'=>$md5zf_pass );
			$this->my_money_mod->edit('user_id='.$user_id,$newpass_array);
			
			if ( $_POST['ret_url'] )//注册成功后返回购物页面
			{
				$this->show_message('支付密码设置成功', '返回来源页', rawurldecode($_POST['ret_url']));
			}else{
				$this->show_message('支付密码设置成功', '会员中心', 'index.php?app=member');
			}
			return;
		}
		else
		{
			if (!empty($_GET['ret_url']))
			{
				$ret_url = htmldecode($_GET['ret_url']);
			}else{
				if (isset($_SERVER['HTTP_REFERER']))
				{
					$ret_url = $_SERVER['HTTP_REFERER'];
				}else{
					$ret_url = site_url() . '/index.php';
				}
			}
			$this->assign('ret_url', rawurlencode($ret_url));				
            $this->import_resource(array(
                'script' => 'jquery.plugins/jquery.validate.js',
            ));		
			$this->assign('money_pass', $money_pass);	
            $this->_config_seo('title', '设置支付宝密码 - ' . Conf::get('site_name'));
			$this->assign('curitem', '设置支付宝密码');		
			$this->display('my_money.setpaypassword.html');
		}
	}

    /**
     *    生成订单号
     */
    function _gen_order_sn()
    {
        /* 选择一个随机的方案 */
        mt_srand((double) microtime() * 1000000);
        $timestamp = gmtime();
        $y = date('y', $timestamp);
        $z = date('z', $timestamp);
        $order_sn = $y . str_pad($z, 3, '0', STR_PAD_LEFT) . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);

        $model_order =& m('my_moneylog');
        $orders = $model_order->find('pay_order_sn=' . $order_sn);
        if (empty($orders))
        {
            /* 否则就使用这个订单号 */
            return $order_sn;
        }

        /* 如果有重复的，则重新生成 */
        return $this->_gen_order_sn();
    }	
    /**
     * 构造15位的随机字符串
     *
     * @return string | 生成的字符串
     */
    function _rand()
    {
        $word = $this->generate_code();
        return $word;
    }

    function generate_code($len = 15)
    {
        $chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        for ($i = 0, $count = strlen($chars); $i < $count; $i++)
        {
            $arr[$i] = $chars[$i];
        }

        mt_srand((double) microtime() * 1000000);
        shuffle($arr);
        $code = substr(implode('', $arr), 5, $len);
        return $code;
    }

}
?>
